package team.wuyou.util.encryption;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author ck
 * @Time 2022年03月10日1:31
 */
public class MD5Utils {

    public static void main(String[] args) {
        String password = "pass19";
        password = MD5Utils.MD5Encode(password,"UTF-8",10,false);
        System.out.println("最终："+password);
    }

     // 16进制的字符串数组
    private final static String[] hexDigitsStrings = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"
            , "d", "e", "f"};

     // 16进制的字符集
    private final static char[] hexDigitsChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D'
            , 'E', 'F'};

    /**
     * MD5加密字符串*
     * @param source 源字符串
     * @return加密后的字符串*
     */
    public static String getMD5(String source) {
        String mdString = null;
        if (source != null) {
            mdString = getMD5(source.getBytes(StandardCharsets.UTF_8));
        }
        return mdString;
    }

    /**
     * MD5加密以byte数组表示的字符串
     * @param source 源字节数组
     * @return加密后的字符串
     */
    public static String getMD5(byte[] source) {
        String s = null;
        final int temp = 0xf;
        final int arraysize = 32;
        final int strLen = 16;
        final int offset = 4;
        try {
            MessageDigest md = MessageDigest
                    .getInstance("MD5");
            md.update(source);
            byte[] tmp = md.digest();
            char[] str = new char[arraysize];
            int k = 0;
            for (int i = 0; i < strLen; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigitsChar[byte0 >>> offset & temp];
                str[k++] = hexDigitsChar[byte0 & temp];
            }
            s = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 获取文件的MD5值
     * @param file 目标文件
     * @return MD5字符串
     * @throws Exception
     */
    public static String getFileMD5String(File file) throws Exception {
        String ret = "";
        FileInputStream in = null;
        FileChannel ch = null;
        try {
            in = new FileInputStream(file);
            ch = in.getChannel();
            ByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
                    file.length());
            MessageDigest messageDigest = MessageDigest.getInstance("D5");
            messageDigest.update(byteBuffer);
            ret = byteArrayToHexString(messageDigest.digest());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ch != null) {
                try {
                    ch.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }

    /**
     *  获取文件的md5值
     * @author ck
     * @date 2022/3/10 2:05
     * @param fileName 目标文件的完整名称
     * @return java.lang.String MD5字符串
     * @throws Exception
     */
    public static String getFileMD5String(String fileName) throws Exception{
        return getFileMD5String(new File(fileName));
    }

    /**
     * 加密
     * @author ck
     * @date 2022/3/10 2:11
     * @param source 需要加密的原字符串
     * @param encoding 指定编码类型
     * @param uppercase 是否转为大写字符串
     * @return java.lang.String
     */
    public static String MD5Encode(String source, String encoding, boolean uppercase ){
        String result = null ;
        try {
            result = source;
            // 获取MD5摘要对象
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 使用指定的字节数组更新摘要信息
            messageDigest.update(result.getBytes(encoding));
            //
            result = byteArrayToHexString(messageDigest.digest());
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return uppercase? result.toUpperCase():result ;
    }
    /**
     * @Description //TODO 
     * @Param [java.lang.String[]]
     * @return void
     * @Date 2023/11/30 15:26
     * @Author xing
     * source 需要加密的字符串
     * num 加密的次数（10，100，1000等）
     * encoding 加密格式（UTF-8、GBK等）
     * uppercase 是否大写（true，false）
     **/
    public static String MD5Encode(String source, String encoding,int num,boolean uppercase){
        for(int i=0;i<num;i++) {
            source = MD5Encode(source, encoding, uppercase);
        }
       return source;
    }
    
    /**
     * 转换字节数组为16进制字符串
     * @author ck
     * @date 2022/3/10 2:11
     * @param digest 字节数组
     * @return java.lang.String
     */
    private static String byteArrayToHexString(byte[] digest) {
        StringBuilder stringBuilder = new StringBuilder();
        for (byte item : digest){
            stringBuilder.append(byteToHexString(item));
        }
        return stringBuilder.toString();
    }

    /**
     * 将字节数组中指定区间的子数组转换成16进制字符串
     * @author ck
     * @date 2022/3/10 2:22
     * @param bytes 目标啊字节数组
     * @param start 起始位置(包括该位置)
     * @param end 结束位置(不包括该位置)
     * @return java.lang.String 转换结果
     */
    public static String bytesToHex(byte[] bytes,int start , int end){
        StringBuilder sb = new StringBuilder();
        for (int i = start ; i < start + end ; i++){
            sb.append(byteToHexString(bytes[i]));
        }
        return sb.toString();
    }
    /**
     * 转换byte到16进制
     * @author ck
     * @date 2022/3/10 2:14
     * @param item 要转换的byte
     * @return java.lang.String 16进制对应的字符
     */
    private static String byteToHexString(byte item) {
        int n = item;
        if (n < 0){
            n = 256+n ;
        }
        int d1 = n/16 ;
        int d2 = n%16 ;
        return hexDigitsStrings[d1] + hexDigitsStrings[d2];
    }
}

